<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, View, Edit, Delete, Upload, Download } from '@element-plus/icons-vue'
import request from '../utils/request'
import { EMPLOYEE_API, LEAVE_API } from '../config/api'

// 响应式数据
const loading = ref(false)
const addingEmployee = ref(false)
const editingEmployee = ref(false)
const submittingLeave = ref(false)
const processingPromotion = ref(false)
const showAddEmployeeDialog = ref(false)
const showEditEmployeeDialog = ref(false)
const showLeaveDialog = ref(false)
const showPromotionDialog = ref(false)
const showLeaveListDialog = ref(false)
const activeLeaveTab = ref('leave')
const searchQuery = ref('')
const searchStoreId = ref('')
const leaveRequests = ref([])
const leaveLoading = ref(false)

// 导入文件相关
const importingEmployees = ref(false)
const importResult = ref(null)
const showImportResult = ref(false)
const fileInputRef = ref()

// 表单引用
const addEmployeeFormRef = ref()
const editEmployeeFormRef = ref()
const leaveFormRef = ref()
const restFormRef = ref()

// 当前用户信息
const currentUserRole = ref('')
const currentUserId = ref('')

// 员工列表
const employees = ref([])
const filteredEmployees = ref([])
const storeOptions = ref([])

const loadStores = async () => {
  try {
    const res = await request.get('/api/stores', { params: { page: 1, limit: 1000 } })
    // 兼容不同返回格式
    const stores = res.data?.data?.stores || res.data?.data || res.data?.stores || []
    storeOptions.value = stores
  } catch (e) {
    console.error('加载门店失败', e)
  }
}

// 选中的员工
const selectedEmployee = ref(null)
const newRole = ref('')

// 添加员工表单
const addEmployeeForm = reactive({
  name: '',
  phone: '',
  password: '',
  role: 'employee',
  storeId: ''
})

// 编辑员工表单
const editEmployeeForm = reactive({
  id: '',
  name: '',
  phone: '',
  role: 'employee',
  status: 'active',
  storeId: ''
})

// 请假表单
const leaveForm = reactive({
  type: '',
  startDate: '',
  endDate: '',
  reason: ''
})

// 休息表单
const restForm = reactive({
  restDate: '',
  reason: ''
})

// 表单验证规则
const addEmployeeRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入初始密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ]
}

const editEmployeeRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择员工状态', trigger: 'change' }
  ]
}

const leaveRules = {
  type: [
    { required: true, message: '请选择请假类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' }
  ]
}

const restRules = {
  restDate: [
    { required: true, message: '请选择休息日期', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入休息原因', trigger: 'blur' }
  ]
}

// 计算属性
const canAddEmployee = computed(() => {
  return ['owner', 'manager'].includes(currentUserRole.value)
})

const canEditEmployee = computed(() => {
  return ['owner', 'manager'].includes(currentUserRole.value)
})

const canPromote = computed(() => {
  return currentUserRole.value === 'owner'
})

const canManageLeave = computed(() => {
  return ['owner', 'manager'].includes(currentUserRole.value)
})

const canApproveLeave = computed(() => {
  return currentUserRole.value === 'owner'
})

const canChangeStatus = computed(() => {
  return ['owner', 'manager'].includes(currentUserRole.value)
})

const promotionTitle = computed(() => {
  if (!selectedEmployee.value) return ''
  const role = selectedEmployee.value.role
  return (role === '员工' || role === 'employee') ? '员工升职' : '管理员降职'
})

// 统计计算属性
const totalEmployees = computed(() => employees.value.length)

const activeEmployees = computed(() => 
  employees.value.filter(emp => emp.status === 'active').length
)

const managerCount = computed(() => 
  employees.value.filter(emp => 
    emp.role === 'manager' || emp.role === '管理员'
  ).length
)

const pendingLeaveCount = computed(() => 
  leaveRequests.value.filter(req => req.status === 'pending').length
)

// 方法
const getRoleText = (role) => {
  const roleMap = {
    'owner': '老板',
    'manager': '管理员',
    'employee': '员工'
  }
  return roleMap[role] || '未知'
}

const getRoleTagType = (role) => {
  const typeMap = {
    'owner': 'danger',
    'manager': 'warning',
    'employee': 'info',
    '老板': 'danger',
    '管理员': 'warning',
    '员工': 'info'
  }
  return typeMap[role] || 'info'
}

const getLeaveTypeText = (type) => {
  const typeMap = {
    'personal': '事假',
    'sick': '病假',
    'annual': '年假',
    'other': '其他'
  }
  return typeMap[type] || '未知'
}

const getLeaveStatusText = (status) => {
  const statusMap = {
    'pending': '待审批',
    'approved': '已批准',
    'rejected': '已拒绝'
  }
  return statusMap[status] || '未知'
}

const getLeaveStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取员工出勤状态文本
const getAttendanceStatusText = (employee) => {
  // 如果员工状态不是在职，直接返回离职
  if (employee.status !== 'active') {
    return '离职'
  }
  
  // 查找该员工的请假记录
  const employeeLeaveRequests = leaveRequests.value.filter(req => 
    req.employeeId === employee._id || req.employeeId === employee.id
  )
  
  // 检查是否有已批准的请假记录且包含今天
  const today = new Date().toISOString().split('T')[0]
  const approvedLeaveToday = employeeLeaveRequests.find(req => 
    req.status === 'approved' && 
    req.startDate <= today && 
    req.endDate >= today
  )
  
  if (approvedLeaveToday) {
    return '请假中'
  }
  
  // 检查是否有待审批的请假记录且包含今天
  const pendingLeaveToday = employeeLeaveRequests.find(req => 
    req.status === 'pending' && 
    req.startDate <= today && 
    req.endDate >= today
  )
  
  if (pendingLeaveToday) {
    return '请假待审批'
  }
  
  return '正常出勤'
}

// 获取员工出勤状态类型
const getAttendanceStatusType = (employee) => {
  // 如果员工状态不是在职，返回危险类型
  if (employee.status !== 'active') {
    return 'danger'
  }
  
  // 查找该员工的请假记录
  const employeeLeaveRequests = leaveRequests.value.filter(req => 
    req.employeeId === employee._id || req.employeeId === employee.id
  )
  
  // 检查是否有已批准的请假记录且包含今天
  const today = new Date().toISOString().split('T')[0]
  const approvedLeaveToday = employeeLeaveRequests.find(req => 
    req.status === 'approved' && 
    req.startDate <= today && 
    req.endDate >= today
  )
  
  if (approvedLeaveToday) {
    return 'warning'
  }
  
  // 检查是否有待审批的请假记录且包含今天
  const pendingLeaveToday = employeeLeaveRequests.find(req => 
    req.status === 'pending' && 
    req.startDate <= today && 
    req.endDate >= today
  )
  
  if (pendingLeaveToday) {
    return 'info'
  }
  
  return 'success'
}

// 格式化日期为 YYYY-MM-DD 格式
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    return date.toISOString().split('T')[0]
  } catch (error) {
    return dateString
  }
}

const loadEmployees = async () => {
  try {
    loading.value = true
    
    const response = await request.get(EMPLOYEE_API.GET_EMPLOYEES)
    
    if (response.data && response.data.success) {
      employees.value = response.data.data || []
      filteredEmployees.value = [...employees.value]
    } else {
      ElMessage.error(response.data?.message || '加载员工列表失败')
    }
  } catch (error) {
    ElMessage.error('加载员工列表失败')
    console.error('加载员工列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadLeaveRequests = async () => {
  try {
    leaveLoading.value = true
    
    const response = await request.get(LEAVE_API.GET_LEAVE_REQUESTS)
    
    if (response.data && response.data.success) {
      leaveRequests.value = response.data.data || []
    } else {
      ElMessage.error(response.data?.message || '加载请假申请列表失败')
    }
  } catch (error) {
    ElMessage.error('加载请假申请列表失败')
    console.error('加载请假申请列表失败:', error)
  } finally {
    leaveLoading.value = false
  }
}

const handleSearch = () => {
  let filtered = [...employees.value]
  
  // 按姓名或工号搜索
  if (searchQuery.value) {
    filtered = filtered.filter(employee => 
      employee.name.includes(searchQuery.value) ||
      employee.employeeId.includes(searchQuery.value)
    )
  }
  
  // 按门店搜索
  if (searchStoreId.value) {
    if (searchStoreId.value === 'null') {
      // 筛选无门店的员工
      filtered = filtered.filter(employee => 
        !employee.storeId || employee.storeId === null
      )
    } else {
      // 筛选指定门店的员工
      filtered = filtered.filter(employee => 
        employee.storeId === searchStoreId.value
      )
    }
  }
  
  filteredEmployees.value = filtered
}

const handleAddEmployee = async () => {
  try {
    await addEmployeeFormRef.value.validate()
    addingEmployee.value = true
    
    const response = await request.post(EMPLOYEE_API.CREATE_EMPLOYEE, addEmployeeForm)
    
    if (response.data && response.data.success) {
      ElMessage.success('员工添加成功')
      showAddEmployeeDialog.value = false
      resetAddEmployeeForm()
      // 重新加载员工列表和请假记录
      await loadEmployees()
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '添加员工失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('添加员工失败')
    }
    console.error('添加员工失败:', error)
  } finally {
    addingEmployee.value = false
  }
}

// 导入文件相关方法
const handleImportFile = () => {
  fileInputRef.value?.click()
}

const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel'
  ]
  
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('请选择Excel文件（.xlsx或.xls格式）')
    return
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过5MB')
    return
  }
  
  try {
    importingEmployees.value = true
    
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await request.post(EMPLOYEE_API.IMPORT_EMPLOYEES, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data && response.data.success) {
      importResult.value = response.data
      showImportResult.value = true
      ElMessage.success(response.data.message)
      
      // 关闭添加员工弹框
      showAddEmployeeDialog.value = false
      
      // 重新加载员工列表和请假记录
      await loadEmployees()
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '导入失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.response?.data?.errors) {
      // 显示详细的错误信息
      const errorMessages = error.response.data.errors.join('\n')
      ElMessage.error(`导入失败：\n${errorMessages}`)
    } else {
      ElMessage.error('导入失败')
    }
    console.error('导入员工失败:', error)
  } finally {
    importingEmployees.value = false
    // 清空文件输入
    event.target.value = ''
  }
}

const downloadTemplate = () => {
  // 创建CSV格式的模板数据
  const templateData = [
    ['姓名', '电话', '初始密码', '职位'],
    ['张三', '13800138000', '123456', '员工'],
    ['李四', '13900139000', '123456', '管理员']
  ]
  
  // 转换为CSV格式
  const csvContent = templateData.map(row => row.join(',')).join('\n')
  
  // 添加BOM以确保Excel正确识别中文
  const BOM = '\uFEFF'
  const csvWithBOM = BOM + csvContent
  
  // 创建Blob并下载
  const blob = new Blob([csvWithBOM], { type: 'text/csv;charset=utf-8;' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = '员工导入模板.csv'
  link.click()
  window.URL.revokeObjectURL(url)
  
  ElMessage.success('模板下载成功，请将文件另存为Excel格式(.xlsx)')
}

const resetAddEmployeeForm = () => {
  addEmployeeForm.name = ''
  addEmployeeForm.phone = ''
  addEmployeeForm.password = ''
  addEmployeeForm.role = 'employee'
  addEmployeeFormRef.value?.resetFields()
}

const handleEditEmployee = (employee) => {
  selectedEmployee.value = employee
  editEmployeeForm.id = employee._id || employee.id
  editEmployeeForm.name = employee.name
  editEmployeeForm.phone = employee.phone || ''
  
  // 修复角色映射逻辑
  let role = 'employee'
  if (employee.role === '老板' || employee.role === 'owner') {
    role = 'owner'
  } else if (employee.role === '管理员' || employee.role === 'manager') {
    role = 'manager'
  }
  
  editEmployeeForm.role = role
  editEmployeeForm.status = employee.status || 'active'
  editEmployeeForm.storeId = employee.storeId || ''
  showEditEmployeeDialog.value = true
  
  console.log('编辑员工:', employee, '映射角色:', role)
}

const resetEditEmployeeForm = () => {
  editEmployeeForm.id = ''
  editEmployeeForm.name = ''
  editEmployeeForm.phone = ''
  editEmployeeForm.role = 'employee'
  editEmployeeForm.status = 'active'
  editEmployeeFormRef.value?.resetFields()
}

const handleUpdateEmployee = async () => {
  try {
    await editEmployeeFormRef.value.validate()
    editingEmployee.value = true
    
    const updateData = {
      name: editEmployeeForm.name,
      phone: editEmployeeForm.phone,
      role: editEmployeeForm.role,
      status: editEmployeeForm.status,
      storeId: editEmployeeForm.storeId || null
    }
    
    const response = await request.put(EMPLOYEE_API.UPDATE_EMPLOYEE(editEmployeeForm.id), updateData)
    
    if (response.data && response.data.success) {
      ElMessage.success('员工信息更新成功')
      showEditEmployeeDialog.value = false
      resetEditEmployeeForm()
      // 重新加载员工列表和请假记录
      await loadEmployees()
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '更新员工信息失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('更新员工信息失败')
    }
    console.error('更新员工信息失败:', error)
  } finally {
    editingEmployee.value = false
  }
}

const handleLeaveManagement = (employee) => {
  selectedEmployee.value = employee
  showLeaveDialog.value = true
  resetLeaveForms()
}

const resetLeaveForms = () => {
  leaveForm.type = ''
  leaveForm.startDate = ''
  leaveForm.endDate = ''
  leaveForm.reason = ''
  restForm.restDate = ''
  restForm.reason = ''
  leaveFormRef.value?.resetFields()
  restFormRef.value?.resetFields()
}

const handleSubmitLeave = async () => {
  try {
    if (activeLeaveTab.value === 'leave') {
      await leaveFormRef.value.validate()
      await submitLeaveRequest()
    } else {
      await restFormRef.value.validate()
      await submitRestRequest()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

const submitLeaveRequest = async () => {
  try {
    submittingLeave.value = true
    
    const leaveData = {
      employeeId: selectedEmployee.value._id || selectedEmployee.value.id, // 使用真实的MongoDB ID
      type: leaveForm.type,
      startDate: leaveForm.startDate,
      endDate: leaveForm.endDate,
      reason: leaveForm.reason,
      category: 'leave'
    }
    
    const response = await request.post(LEAVE_API.CREATE_LEAVE_REQUEST, leaveData)
    
    if (response.data && response.data.success) {
      ElMessage.success('请假申请提交成功')
      showLeaveDialog.value = false
      resetLeaveForms()
      // 重新加载请假申请列表
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交请假申请失败')
    console.error('提交请假申请失败:', error)
  } finally {
    submittingLeave.value = false
  }
}

const submitRestRequest = async () => {
  try {
    submittingLeave.value = true
    
    const restData = {
      employeeId: selectedEmployee.value._id || selectedEmployee.value.id, // 使用真实的MongoDB ID
      restDate: restForm.restDate,
      reason: restForm.reason,
      category: 'rest'
    }
    
    const response = await request.post(LEAVE_API.CREATE_LEAVE_REQUEST, restData)
    
    if (response.data && response.data.success) {
      ElMessage.success('休息安排提交成功')
      showLeaveDialog.value = false
      resetLeaveForms()
      // 重新加载请假申请列表
      await loadLeaveRequests()
      // 重新加载员工列表
      await loadEmployees()
    } else {
      ElMessage.error(response.data?.message || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交休息安排失败')
    console.error('提交休息安排失败:', error)
  } finally {
    submittingLeave.value = false
  }
}

const handlePromotion = (employee) => {
  selectedEmployee.value = employee
  const currentRole = employee.role
  newRole.value = (currentRole === '员工' || currentRole === 'employee') ? 'manager' : 'employee'
  showPromotionDialog.value = true
  
  console.log('升职/降职:', employee.name, '当前角色:', currentRole, '新角色:', newRole.value)
}

const confirmPromotion = async () => {
  try {
    processingPromotion.value = true
    
    const response = await request.put(EMPLOYEE_API.UPDATE_EMPLOYEE_ROLE(selectedEmployee.value._id || selectedEmployee.value.id), {
      newRole: newRole.value
    })
    
    if (response.data && response.data.success) {
      ElMessage.success('职位调整成功')
      showPromotionDialog.value = false
      // 重新加载员工列表和请假记录
      await loadEmployees()
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '调整失败')
    }
  } catch (error) {
    ElMessage.error('职位调整失败')
    console.error('职位调整失败:', error)
  } finally {
    processingPromotion.value = false
  }
}

const handleStatusChange = async (employee) => {
  try {
    const newStatus = employee.status === 'active' ? 'inactive' : 'active'
    const actionText = newStatus === 'active' ? '设为在职' : '设为离职'
    
    console.log('状态变更:', { employee, newStatus, actionText })
    
    await ElMessageBox.confirm(
      `确认要将 ${employee.name} ${actionText}吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.put(EMPLOYEE_API.UPDATE_EMPLOYEE_STATUS(employee._id || employee.id), {
      newStatus
    })
    
    if (response.data && response.data.success) {
      ElMessage.success(`${actionText}成功`)
      // 重新加载员工列表和请假记录
      await loadEmployees()
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('状态更新失败')
      console.error('状态更新失败:', error)
    }
  }
}

const handleApproveLeave = async (leaveRequest) => {
  try {
    await ElMessageBox.confirm(
      `确认批准 ${leaveRequest.employeeName} 的请假申请吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.put(LEAVE_API.APPROVE_LEAVE_REQUEST(leaveRequest.id))
    
    if (response.data && response.data.success) {
      ElMessage.success('请假申请已批准')
      // 重新加载请假申请列表
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error('操作失败:', error)
    }
  }
}

const handleRejectLeave = async (leaveRequest) => {
  try {
    await ElMessageBox.confirm(
      `确认拒绝 ${leaveRequest.employeeName} 的请假申请吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.put(LEAVE_API.REJECT_LEAVE_REQUEST(leaveRequest.id))
    
    if (response.data && response.data.success) {
      ElMessage.success('请假申请已拒绝')
      // 重新加载请假申请列表
      await loadLeaveRequests()
    } else {
      ElMessage.error(response.data?.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error('操作失败:', error)
    }
  }
}

const loadCurrentUser = () => {
  try {
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      // 修复角色映射：将中文角色名映射为英文
      let role = user.role || ''
      if (role === '老板') {
        role = 'owner'
      } else if (role === '管理员') {
        role = 'manager'
      } else if (role === '员工') {
        role = 'employee'
      }
      currentUserRole.value = role
      currentUserId.value = user.id || ''
      
      console.log('当前用户角色:', role, '原始角色:', user.role)
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}



// 生命周期
onMounted(() => {
  loadCurrentUser()
  loadEmployees()
  loadLeaveRequests()
  loadStores()
})
</script>

<template>
  <div class="manage-person-container" v-loading="loading">
    <el-card class="page-header">
      <template #header>
                <div class="card-header">
          <span class="title">员工管理</span>
          <div class="header-actions">
            
            <el-button 
              type="info" 
              @click="showLeaveListDialog = true" 
              v-if="canManageLeave"
              style="margin-right: 10px;"
            >
              <el-icon><View /></el-icon>
              查看请假申请
            </el-button>
            <el-button type="primary" @click="showAddEmployeeDialog = true" v-if="canAddEmployee">
              <el-icon><Plus /></el-icon>
              添加员工
            </el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 统计信息卡片 -->
    <el-card class="stats-card">
      <template #header>
        <div class="card-header">
          <span>员工统计</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ totalEmployees }}</div>
            <div class="stat-label">总员工数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ activeEmployees }}</div>
            <div class="stat-label">在职员工</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ managerCount }}</div>
            <div class="stat-label">管理员</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ pendingLeaveCount }}</div>
            <div class="stat-label">待审批请假</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 员工列表 -->
    <el-card class="employee-list-card">
      <template #header>
        <div class="card-header">
          <span>员工列表</span>
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-input
              v-model="searchQuery"
              placeholder="搜索员工姓名或工号"
              style="width: 250px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="searchStoreId"
              placeholder="选择门店筛选"
              style="width: 200px"
              clearable
              @change="handleSearch"
            >
              <el-option label="全部门店" value="" />
              <el-option label="无门店" value="null" />
              <el-option v-for="store in storeOptions" :key="store._id" :label="store.name" :value="store._id" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table :data="filteredEmployees" style="width: 100%" v-loading="loading">
        <el-table-column prop="employeeId" label="工号" width="100" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="role" label="职位" width="120">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ scope.row.role || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storeName" label="所属门店" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="出勤" width="120">
          <template #default="scope">
            <el-tag :type="getAttendanceStatusType(scope.row)">
              {{ getAttendanceStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinDate" label="入职日期" width="120" />
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEditEmployee(scope.row)"
              v-if="canEditEmployee"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="info" 
              @click="handleLeaveManagement(scope.row)"
              v-if="canManageLeave"
            >
              请假管理
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="handlePromotion(scope.row)"
              v-if="canPromote && scope.row.role !== '老板' && scope.row.role !== 'owner'"
            >
              {{ (scope.row.role === '员工' || scope.row.role === 'employee') ? '升职' : '降职' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleStatusChange(scope.row)"
              v-if="canChangeStatus"
            >
              {{ scope.row.status === 'active' ? '设为离职' : '设为在职' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加员工对话框 -->
    <el-dialog
      v-model="showAddEmployeeDialog"
      title="添加员工"
      width="600px"
      :close-on-click-modal="false"
    >
      <!-- 导入文件区域 -->
      <div class="import-section" style="margin-bottom: 20px; padding: 15px; background-color: #f5f7fa; border-radius: 4px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
          <h4 style="margin: 0; color: #606266;">批量导入员工</h4>
          <el-button type="info" size="small" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载模板
          </el-button>
        </div>
        <div style="display: flex; gap: 10px; align-items: center;">
          <el-button 
            type="primary" 
            @click="handleImportFile"
            :loading="importingEmployees"
            :disabled="importingEmployees"
          >
            <el-icon><Upload /></el-icon>
            {{ importingEmployees ? '导入中...' : '选择文件' }}
          </el-button>
          <span style="color: #909399; font-size: 12px;">
            支持 .xlsx 和 .xls 格式，文件大小不超过 5MB
          </span>
        </div>
        <input
          ref="fileInputRef"
          type="file"
          accept=".xlsx,.xls"
          style="display: none"
          @change="handleFileChange"
        />
      </div>

      <!-- 分隔线 -->
      <el-divider content-position="center">或手动添加</el-divider>

      <el-form
        ref="addEmployeeFormRef"
        :model="addEmployeeForm"
        :rules="addEmployeeRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addEmployeeForm.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addEmployeeForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="初始密码" prop="password">
          <el-input 
            v-model="addEmployeeForm.password" 
            type="password" 
            placeholder="请输入初始密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="职位" prop="role">
          <el-select v-model="addEmployeeForm.role" placeholder="请选择职位" style="width: 100%">
            <el-option label="员工" value="employee" />
            <el-option label="管理员" value="manager" v-if="currentUserRole === 'owner'" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属门店">
          <el-select v-model="addEmployeeForm.storeId" placeholder="请选择门店（可空）" filterable style="width: 100%">
            <el-option :label="'无'" :value="''" />
            <el-option v-for="s in storeOptions" :key="s._id" :label="s.name" :value="s._id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddEmployeeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddEmployee" :loading="addingEmployee">
            确认添加
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑员工对话框 -->
    <el-dialog
      v-model="showEditEmployeeDialog"
      title="编辑员工信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editEmployeeFormRef"
        :model="editEmployeeForm"
        :rules="editEmployeeRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editEmployeeForm.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editEmployeeForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="职位" prop="role">
          <el-select v-model="editEmployeeForm.role" placeholder="请选择职位" style="width: 100%">
            <el-option label="员工" value="employee" />
            <el-option label="管理员" value="manager" />
            <el-option label="老板" value="owner" v-if="currentUserRole === 'owner'" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editEmployeeForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属门店">
          <el-select v-model="editEmployeeForm.storeId" placeholder="请选择门店（可空）" filterable style="width: 100%">
            <el-option :label="'无'" :value="''" />
            <el-option v-for="s in storeOptions" :key="s._id" :label="s.name" :value="s._id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditEmployeeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateEmployee" :loading="editingEmployee">
            确认更新
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 请假管理对话框 -->
    <el-dialog
      v-model="showLeaveDialog"
      title="请假管理"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="leave-info">
        <p><strong>员工：</strong>{{ selectedEmployee?.name }}</p>
        <p><strong>工号：</strong>{{ selectedEmployee?.employeeId }}</p>
      </div>
      
      <el-tabs v-model="activeLeaveTab">
        <el-tab-pane label="请假申请" name="leave">
          <el-form
            ref="leaveFormRef"
            :model="leaveForm"
            :rules="leaveRules"
            label-width="100px"
          >
            <el-form-item label="请假类型" prop="type">
              <el-select v-model="leaveForm.type" placeholder="请选择请假类型" style="width: 100%">
                <el-option label="事假" value="personal" />
                <el-option label="病假" value="sick" />
                <el-option label="年假" value="annual" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="leaveForm.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="leaveForm.endDate"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="请假原因" prop="reason">
              <el-input
                v-model="leaveForm.reason"
                type="textarea"
                :rows="3"
                placeholder="请输入请假原因"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="休息安排" name="rest">
          <el-form
            ref="restFormRef"
            :model="restForm"
            :rules="restRules"
            label-width="100px"
          >
            <el-form-item label="休息日期" prop="restDate">
              <el-date-picker
                v-model="restForm.restDate"
                type="date"
                placeholder="选择休息日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="休息原因" prop="reason">
              <el-input
                v-model="restForm.reason"
                type="textarea"
                :rows="3"
                placeholder="请输入休息原因"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLeaveDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitLeave" :loading="submittingLeave">
            确认提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 升职/降职确认对话框 -->
    <el-dialog
      v-model="showPromotionDialog"
      :title="promotionTitle"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="promotion-confirm">
        <p>确认要将 <strong>{{ selectedEmployee?.name }}</strong> 从 
          <el-tag :type="getRoleTagType(selectedEmployee?.role)">
            {{ selectedEmployee?.role || '未知' }}
          </el-tag> 
          调整为 
          <el-tag :type="getRoleTagType(newRole)">
            {{ newRole === 'owner' ? '老板' : newRole === 'manager' ? '管理员' : '员工' }}
          </el-tag> 吗？
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPromotionDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmPromotion" :loading="processingPromotion">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 请假申请列表对话框 -->
    <el-dialog
      v-model="showLeaveListDialog"
      title="请假申请列表"
      width="1200px"
      :close-on-click-modal="false"
      v-loading="leaveLoading"
      class="leave-list-dialog"
      top="5vh"
    >
      <!-- 请假申请统计信息 -->
      <div class="leave-stats" style="margin-bottom: 15px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ leaveRequests.length }}</div>
                <div class="stat-label">总申请数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-content">
                <div class="stat-number warning">{{ leaveRequests.filter(req => req.status === 'pending').length }}</div>
                <div class="stat-label">待审批</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-content">
                <div class="stat-number success">{{ leaveRequests.filter(req => req.status === 'approved').length }}</div>
                <div class="stat-label">已批准</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-content">
                <div class="stat-number danger">{{ leaveRequests.filter(req => req.status === 'rejected').length }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <el-table :data="leaveRequests" style="width: 100%" :max-height="null" border stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="employeeName" label="申请人" width="120" />
        <el-table-column prop="employeeId" label="工号" width="100">
          <template #default="scope">
            {{ scope.row.employeeId?.toString().slice(-6) || scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="请假类型" width="120">
          <template #default="scope">
            <el-tag :type="getLeaveStatusType(scope.row.status)">
              {{ getLeaveTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="请假原因" min-width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getLeaveStatusType(scope.row.status)">
              {{ getLeaveStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button 
                size="small" 
                type="success" 
                @click="handleApproveLeave(scope.row)" 
                v-if="scope.row.status === 'pending' && canApproveLeave"
              >
                批准
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleRejectLeave(scope.row)" 
                v-if="scope.row.status === 'pending' && canApproveLeave"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog
      v-model="showImportResult"
      title="导入结果"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="importResult" class="import-result">
        <!-- 统计信息 -->
        <div class="import-stats" style="margin-bottom: 20px;">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ importResult.data.total }}</div>
                  <div class="stat-label">总记录数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-number success">{{ importResult.data.successCount }}</div>
                  <div class="stat-label">成功导入</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-number danger">{{ importResult.data.failedCount }}</div>
                  <div class="stat-label">导入失败</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-number" :class="importResult.data.successCount > 0 ? 'success' : 'danger'">
                    {{ importResult.data.total > 0 ? Math.round((importResult.data.successCount / importResult.data.total) * 100) : 0 }}%
                  </div>
                  <div class="stat-label">成功率</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 成功导入的员工列表 -->
        <div v-if="importResult.data.created && importResult.data.created.length > 0" style="margin-bottom: 20px;">
          <h4 style="color: #67c23a; margin-bottom: 10px;">✅ 成功导入的员工</h4>
          <el-table :data="importResult.data.created" border stripe size="small">
            <el-table-column prop="employeeId" label="工号" width="100" />
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="phone" label="电话" width="150" />
            <el-table-column prop="role" label="职位" width="100">
              <template #default="scope">
                <el-tag :type="getRoleTagType(scope.row.role)">
                  {{ scope.row.role }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="joinDate" label="入职日期" width="120" />
          </el-table>
        </div>

        <!-- 导入失败的员工列表 -->
        <div v-if="importResult.data.failed && importResult.data.failed.length > 0">
          <h4 style="color: #f56c6c; margin-bottom: 10px;">❌ 导入失败的员工</h4>
          <el-table :data="importResult.data.failed" border stripe size="small">
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="error" label="失败原因" min-width="200" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportResult = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.manage-person-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.employee-list-card {
  margin-bottom: 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.leave-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.leave-info p {
  margin: 5px 0;
  color: #606266;
}

.promotion-confirm {
  text-align: center;
  padding: 20px 0;
}

.promotion-confirm p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 请假申请列表对话框样式 */
:deep(.leave-list-dialog) {
  .el-dialog {
    margin: 5vh auto !important;
  }
  
  .el-dialog__body {
    padding: 15px 20px;
    max-height: 80vh;
    overflow: visible;
  }
  
  .el-table {
    width: 100%;
    
    .el-table__header-wrapper {
      position: sticky;
      top: 0;
      z-index: 10;
      background-color: #f5f7fa;
    }
    
    .el-table__body-wrapper {
      overflow: visible;
    }
    
    .el-table__header {
      th {
        background-color: #f5f7fa !important;
        color: #606266;
        font-weight: 600;
        border-bottom: 2px solid #ebeef5;
      }
    }
    
    .el-table__body {
      tr {
        &:hover {
          background-color: #f0f9ff;
        }
      }
      
      td {
        border-bottom: 1px solid #ebeef5;
        padding: 8px 0;
      }
    }
  }
}

/* 表格内容样式优化 */
:deep(.el-table) {
  .el-table__header {
    background-color: #f5f7fa;
  }
  
  .el-table__row {
    &:hover {
      background-color: #f0f9ff;
    }
  }
  
  .el-table__cell {
    padding: 12px 0;
  }
}

/* 请假申请统计卡片样式 */
.leave-stats {
  .stat-card {
    border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .stat-content {
      text-align: center;
      padding: 10px 0;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 5px;
        
        &.warning {
          color: #e6a23c;
        }
        
        &.success {
          color: #67c23a;
        }
        
        &.danger {
          color: #f56c6c;
        }
      }
      
      .stat-label {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  flex-direction: row;
  gap: 6px;
  justify-content: center;
  align-items: center;
  
  .el-button {
    margin: 0;
    padding: 4px 8px;
    font-size: 11px;
    min-width: 40px;
    height: 28px;
    line-height: 1;
    
    &.el-button--success {
      background-color: #67c23a;
      border-color: #67c23a;
    }
    
    &.el-button--danger {
      background-color: #f56c6c;
      border-color: #f56c6c;
    }
  }
}

:deep(.el-card__header) {
  padding: 15px 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-tag) {
  margin: 0 5px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .manage-person-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .stat-item {
    padding: 10px 0;
  }
  
  .stat-number {
    font-size: 20px;
  }
}

/* 导入相关样式 */
.import-section {
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.import-section:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.import-result {
  .import-stats {
    .stat-card {
      border: none;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      
      .stat-content {
        text-align: center;
        padding: 10px 0;
        
        .stat-number {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 5px;
          
          &.success {
            color: #67c23a;
          }
          
          &.danger {
            color: #f56c6c;
          }
        }
        
        .stat-label {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

/* 请假申请列表响应式设计 */
@media (max-width: 1400px) {
  :deep(.leave-list-dialog) {
    .el-dialog {
      width: 95vw !important;
      margin: 2vh auto !important;
    }
    
    .el-table {
      .el-table__body-wrapper {
        overflow-x: auto;
      }
    }
  }
}
</style>